<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card style="padding:0 20px">
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog = true"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="roleList">
              <el-table-column label="序号" width="120">
                <template #default="{$index}">
                  {{ ( page.page - 1 ) * page.pagesize + ( $index + 1 ) }}
                </template>
              </el-table-column>
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="assignPermission(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="edit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page.sync="page.page"
                :page-size="page.pagesize"
                layout="prev, pager, next"
                :total="total"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 弹框 -->
      <el-dialog :title="roleForm.id?'编辑弹层':'新增弹层'" :visible="showDialog" @close="btnCancel">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限弹框 -->
      <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
        <!-- 放置一个组件 来显示 权限的树形结构 el-tree  el-table -->
        <el-tree
          ref="permTree"
          :data="permData"
          :props="defaultProps"
          default-expand-all
          show-checkbox
          check-strictly
          node-key="id"
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnPermCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnPermOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getCompanyById } from '@/api/company.js'
import { getRoleList, deleteRoleById, addRole, getRoleDetailById, updateRoleById, assignPerm } from '@/api/role.js'
import { mapGetters } from 'vuex'
import { getPermissionList } from '@/api/permission'
import { dataTransform } from '@/utils'
export default {
  data() {
    // 角色名校验
    const validateName = async(rule, value, callback) => {
      // 定义一个布尔值
      let isRepeat = false
      // 获取部门列表
      const { rows } = await getRoleList({ page: 1, pagesize: this.total })
      // 编辑
      isRepeat = rows.some(v => v.name === value && v.id !== this.roleForm.id)
      // 处理
      if (isRepeat) {
        callback(new Error('角色名称不可重复'))
      } else {
        callback()
      }
    }
    return {
      // 公司信息
      formData: {},
      // 角色列表
      roleList: [],
      // 分页数据
      page: {
        page: 1,
        pagesize: 6
      },
      // 评论总条数
      total: 0,
      // 弹框是否显示
      showDialog: false,
      // 角色表单
      roleForm: {
        name: '',
        description: ''
      },
      // 角色名称校验规则
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { trigger: 'blur', validator: validateName }
        ],
        description: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      // 分配权限弹框
      showPermDialog: false,
      defaultProps: {
        label: 'name'
      },
      // 全部权限列表
      permData: [],
      // 选中权限列表
      selectCheck: [],
      // 角色id
      roleId: ''
    }
  },
  computed: {
    // 公司id
    ...mapGetters(['companyId'])
  },
  async mounted() {
    // 获取企业信息
    const res = await getCompanyById(this.companyId)
    this.formData = res
    // 获取公司角色列表
    this.getRoles()
  },
  methods: {
    // 封装获取公司角色列表
    async getRoles() {
      const { rows, total } = await getRoleList(this.page)
      this.roleList = rows
      this.total = total
    },
    // 分页
    handleCurrentChange(val) {
      this.page.page = val
      this.getRoles()
    },
    // 删除按钮
    async del(id) {
      try {
        await this.$confirm('确定删除该角色吗?', '温馨提示', {

          type: 'warning'
        })
        // 删除
        await deleteRoleById(id)
        // 如果是最后一条
        if (this.roleList.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        // 获取列表
        this.getRoles()
        // 提示
        this.$message.success('删除成功')
        // 判断是否是最后一条
      } catch (error) {
        console.log(error)
      }
    },
    // 取消按钮
    btnCancel() {
      this.showDialog = false
      // 重置数据
      this.roleForm = {
        name: '',
        description: ''
      }
      // 重置校验结果
      this.$refs.roleForm.resetFields()
    },
    // 确认按钮
    async btnOK() {
      // 发请求前校验
      this.$refs.roleForm.validate()
      // 发请求
      if (this.roleForm.id) {
        // 编辑
        await updateRoleById(this.roleForm)
      } else {
        // 新增
        await addRole(this.roleForm)
      }
      // 提示
      this.$message.success('操作成功')
      // 刷新页面
      this.getRoles()
      // 关闭弹窗
      this.showDialog = false
    },
    // 编辑按钮
    async edit(id) {
      // 获取员工详情回填
      const res = await getRoleDetailById(id)
      this.roleForm = res
      this.showDialog = true
    },
    // 分配权限按钮
    async assignPermission(id) {
      this.roleId = id
      // 获取全部权限列表
      this.permData = dataTransform(await getPermissionList(), '0')
      // 获取选中权限
      const { permIds } = await getRoleDetailById(id)
      this.selectCheck = permIds
      this.showPermDialog = true
      this.$nextTick(() => {
        this.$refs.permTree.setCheckedKeys(this.selectCheck)
      })
    },
    // 分配权限取消
    btnPermCancel() {
      this.$refs.permTree.setCheckedKeys([])
      this.showPermDialog = false
    },
    // 分配权限确认
    async btnPermOK() {
      // 发请求
      await assignPerm({
        id: this.roleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      // 提示
      this.$message.success('分配权限成功')
      // 关闭弹窗
      this.showPermDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px 30px;
}
</style>
